import { getUserTagDetail, userTagAdd, userTagUpdate } from "@/services/labelManage";
import { Drawer, Form, Input, Button, Select, Icon, InputNumber, DatePicker, TimePicker, message } from "antd";
import moment from "moment";
import React from "react";

class EditLabel extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible:false,
      title:'添加用户标签',
      userTagItemList:[{group:this.getRadomId(),userTagConditionList:[{id:this.getRadomId()}]}],
      loading:false,
      id:null
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  onOpenDrawer = row => {
    this.setState({
      visible:true,
      title:row ? '编辑用户标签' : '添加用户标签',
      id:row ? row.id : null
    },() => {
      if(row && row.id){
        this.getDetail()
      }
    })
  }

  getDetail = async () => {
    const { id } = this.state;
    const res = await getUserTagDetail({tagId:id})
    console.log(res);
    let groupList = [];
    for(const groupIndex in res.userTagItemList){
      const group = res.userTagItemList[groupIndex];
      let itemList = [];
      for(const itemIndex in group.userTagConditionList){
        const item = group.userTagConditionList[itemIndex]
        itemList.push({id:item.id,info:item})
      }
      groupList.push({group:group.id,userTagConditionList:itemList,groupInfo:group})
    }
    console.log(groupList);
    this.setState({
      userTagItemList:groupList
    },() => {
      this.setData(res)
    })
    
  }

  setData = (res) => {
    const { userTagItemList } = this.state;
    const form = this.props.form;
    form.setFieldsValue({
      tagName:res.tagName,
      id:res.id
    })
    let obj = {}
    for(const groupIndex in userTagItemList){
      const group = userTagItemList[groupIndex]
      for(const itemIndex in group.userTagConditionList){
        const item = group.userTagConditionList[itemIndex]
        const tag = group.group + '_' +item.id
        obj["columnName_"+tag] = item.info.columnName
        obj["conditionType_"+tag] = item.info.conditionType
        obj["conditionValueType_"+tag] = item.info.conditionValueType
        form.setFieldsValue(obj)
        //1.若conditionValueType为 2: 包含(字符串型), 3: 不包含(字符串型), 4: 等于(字符串型), 5: 不等于(字符串型), 6: 等于(数值型), 7: 不等于(数值型), 8: 大于等于(数值型), 9: 小于等于(数值型), 10: 大于(数值型), 11: 小于(数值型)
        if(item.info.conditionValueType == 2 || 
          item.info.conditionValueType == 3 ||
          item.info.conditionValueType == 4 ||
          item.info.conditionValueType == 5 ||
          item.info.conditionValueType == 6 ||
          item.info.conditionValueType == 7 ||
          item.info.conditionValueType == 8 ||
          item.info.conditionValueType == 9 ||
          item.info.conditionValueType == 10 || 
          item.info.conditionValueType == 11){
          let obj1 = {}
          obj1['conditionValue_'+tag] = item.info.conditionValue
          //因为是conditionValueType控制剩下表单的显隐，所以需要延迟加载，否则会加载失败
            setTimeout(() => {
              form.setFieldsValue(obj1)
            },100)
        }
        //2.若conditionValueType为  12: 大于(时间段), 13: 小于(时间段), 14: 等于(时间段)
        if(item.info.conditionValueType == 12 || 
          item.info.conditionValueType == 13 || 
          item.info.conditionValueType == 14){
            let obj2 = {}
            const conditionValueArr = item.info.conditionValue.split('_');
            obj2['conditionValue_'+tag] = conditionValueArr[0]
            obj2['conditionValueOther_'+tag] = conditionValueArr[1]
            //因为是conditionValueType控制剩下表单的显隐，所以需要延迟加载，否则会加载失败
            setTimeout(() => {
              form.setFieldsValue(obj2)
            },100)
        }
        //2.若conditionValueType为  15: 早于(日期时间), 16: 晚于(日期时间), 17: 等于(日期时间)
        if(item.info.conditionValueType == 15 || 
          item.info.conditionValueType == 16 || 
          item.info.conditionValueType == 17){
            let obj3 = {}
            obj3['conditionValue_'+tag] = moment(item.info.conditionValue)
            obj3['conditionValueOther_'+tag] = moment(item.info.conditionValue)
            //因为是conditionValueType控制剩下表单的显隐，所以需要延迟加载，否则会加载失败
            setTimeout(() => {
              form.setFieldsValue(obj3)
            },100)
        }
        
        
        
      }
    }
    
  }

  onCloseDrawer = () => {
    this.props.form.resetFields()
    this.setState({
      visible:false,
      id:null,
      userTagItemList:[{group:this.getRadomId(),userTagConditionList:[{id:this.getRadomId()}]}],
    })
  }

  // 添加条件且
  addConditionItem = group => {
    let { userTagItemList } = this.state; 
    const index = userTagItemList.findIndex(g => g.group === group)
    if(index > -1){
      userTagItemList[index].userTagConditionList.push({id:this.getRadomId()})
      this.setState({
        userTagItemList
      })
    }
  }

  // 添加条件组或
  addConditionGroup = () => {
    let { userTagItemList } = this.state;
    userTagItemList.push({group:this.getRadomId(),userTagConditionList:[{id:this.getRadomId()}]})
    this.setState({
      userTagItemList
    })
  }

  //删除条件且
  removeConditionItem = (group,con) => {
    let { userTagItemList } = this.state; 
    const index = userTagItemList.findIndex(g => g.group === group)
    if(index > -1){
      const newConditionList = userTagItemList[index].userTagConditionList.filter(item => item.id != con)
      userTagItemList[index].userTagConditionList = newConditionList
      this.setState({
        userTagItemList
      })
    }
  }

  //删除条件组或
  removeConditionGroup = group => {
    let { userTagItemList } = this.state;
    const newList = userTagItemList.filter(item => item.group != group);
    this.setState({
      userTagItemList:newList
    })
  }

  //修改状态/值 需清空一些表单项
  changeConditionType = (group,con) => {
    this.props.form.resetFields([
      'conditionValueType_'+group+'_'+con,
      'conditionValue_'+group+'_'+con,
      'conditionValueOther_'+group+'_'+con
    ])
  }

  //修改条件类型 需清空一些表单项
  changeConditionValueType = (group,con) => {
    this.props.form.resetFields([
      'conditionValue_'+group+'_'+con,
      'conditionValueOther_'+group+'_'+con
    ])
  }

  getRadomId = () => {
    function S4() {
			return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
		}
		return ( S4() + S4() );
  }

  doValidate = () => {
    const that = this;
    that.props.form.validateFields((error,values) => {
      if(!error){
        console.log(values);
        const { userTagItemList,id } = that.state;
        let groupList = []
        for(const groupIndex in userTagItemList){
          const group = userTagItemList[groupIndex];
          let itemList = [];
          for(const itemIndex in group.userTagConditionList){
            const item = group.userTagConditionList[itemIndex];
            const tag = group.group+'_'+item.id
            let obj = {
              columnName:values['columnName_'+tag],
              conditionType:values['conditionType_'+tag],
              conditionValueType:values['conditionValueType_'+tag]
            }
            //1.若conditionValueType为 2: 包含(字符串型), 3: 不包含(字符串型), 4: 等于(字符串型), 5: 不等于(字符串型), 6: 等于(数值型), 7: 不等于(数值型), 8: 大于等于(数值型), 9: 小于等于(数值型), 10: 大于(数值型), 11: 小于(数值型)
            if(values['conditionValueType_'+tag] == 2 || 
            values['conditionValueType_'+tag] == 3 ||
            values['conditionValueType_'+tag] == 4 ||
            values['conditionValueType_'+tag] == 5 ||
            values['conditionValueType_'+tag] == 6 ||
            values['conditionValueType_'+tag] == 7 ||
            values['conditionValueType_'+tag] == 8 ||
            values['conditionValueType_'+tag] == 9 ||
            values['conditionValueType_'+tag] == 10 || 
            values['conditionValueType_'+tag] == 11){
              obj.conditionValue = values['conditionValue_'+tag]+''
            }
            //2.若conditionValueType为  12: 大于(时间段), 13: 小于(时间段), 14: 等于(时间段)
            if(values['conditionValueType_'+tag] == 12 || 
            values['conditionValueType_'+tag] == 13 || 
            values['conditionValueType_'+tag] == 14){
              obj.conditionValue = values['conditionValue_'+tag]+'_'+values['conditionValueOther_'+tag]
            }
            //2.若conditionValueType为  15: 早于(日期时间), 16: 晚于(日期时间), 17: 等于(日期时间)
            if(values['conditionValueType_'+tag] == 15 || 
            values['conditionValueType_'+tag] == 16 || 
            values['conditionValueType_'+tag] == 17){
              obj.conditionValue = moment(values['conditionValue_'+tag]).format('YYYY-MM-DD')+' '+ moment(values['conditionValueOther_'+tag]).format('HH:mm:ss')
            }
            if(item.info){
              obj.id = item.info.id
              obj.tagItemId = item.info.tagItemId
            }
            itemList.push(obj)
          }
          let groupObj = {
            logic:'1',
            userTagConditionList:itemList
          }
          if(group.groupInfo){
            groupObj.id = group.groupInfo.id
            groupObj.tagId = group.groupInfo.tagId
          }
          groupList.push(groupObj)
        }
        console.log(groupList);
        const params = {
          tagName:values.tagName,
          tagValue:values.tagValue,
          userTagItemList:groupList
        }
        this.doSubmit(params)
      }
    })
  }

  doSubmit = (params) => {
    this.setState({
      loading:true
    },async () => {
      const { id } = this.state;
      let res = {}
      if(id){
        params.id = id;
        res = await userTagUpdate(params)
      }else{
        res = await userTagAdd(params)
      }
      console.log(res);
      if(res.code == 0){
        message.info(res.msg)
        this.onCloseDrawer()
        this.props.refreshList()
      }else{
        //保存失败，只关闭loading
      }
      this.setState({
        loading:false
      })
    })
  }

  render(){
    const { visible,title,userTagItemList,loading ,id} = this.state;
    const { getFieldDecorator,getFieldValue } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
    };
    const groupStyle = {
      marginBottom:10
    }
    const closeStyle = {
      marginRight:10,
      cursor:'pointer'
    }
    const deleteStyle = {
      marginLeft:10,
      cursor:'pointer'
    }
    const conditionStyle = {
      background:'#3e5bff',
      color:'#ffffff',
      borderRadius:'50%',
      padding:'2px 5px',
      verticalAlign: 'middle'
    }
    const inlineStyle = {
      display:'inline-block',
      marginRight:5,
      marginBottom:0
    }
    const dividerStyle = {
      display:'inline-block',
      verticalAlign: 'middle',
      width:'calc(100% - 50px)',
      height:'1px',
      background:'#E8E8E8'
    }
    const columnNameList = [
      {
        value:'name',
        text:'员工姓名'
      },
      {
        value:'department',
        text:'部门'
      },
      {
        value:'position',
        text:'职位'
      },
      {
        value:'mobile',
        text:'手机号码'
      },
      {
        value:'biz_email',
        text:'企业邮箱'
      },
      {
        value:'email',
        text:'email'
      },
      {
        value:'is_leader_in_dept',
        text:'是否为部门负责人'
      },
      {
        value:'im_tag',
        text:'通讯录标签'
      },
    ]
    const conditionTypeList = [
      {
        value:'0',
        text:'状态'
      },
      {
        value:'1',
        text:'值'
      }
    ]
    const conditionValueTypeList0 = [
      {
        value:'0',
        text:'已填充'
      },
      {
        value:'1',
        text:'未填充'
      }
    ]
    const conditionValueTypeList1 = [
      {
        value:'2',
        text:'包含(字符串型)'
      },
      {
        value:'3',
        text:'不包含(字符串型)'
      },
      {
        value:'4',
        text:'等于(字符串型)'
      },
      {
        value:'5',
        text:'不等于(字符串型)'
      },
      {
        value:'6',
        text:'等于(数值型)'
      },
      {
        value:'7',
        text:'不等于(数值型)'
      },
      {
        value:'8',
        text:'大于等于(数值型)'
      },
      {
        value:'9',
        text:'小于等于(数值型)'
      },
      {
        value:'10',
        text:'大于(数值型)'
      },
      {
        value:'11',
        text:'小于(数值型)'
      },
      {
        value:'12',
        text:'大于(时间段)'
      },
      {
        value:'13',
        text:'小于(时间段)'
      },
      {
        value:'14',
        text:'等于(时间段)'
      },
      {
        value:'15',
        text:'早于(日期时间)'
      },
      {
        value:'16',
        text:'晚于(日期时间)'
      },
      {
        value:'17',
        text:'等于(日期时间)'
      },
    ]
    const unitList = [
      {
        value:'年',
        text:'年'
      },
      {
        value:'月',
        text:'月'
      },
      {
        value:'天',
        text:'天'
      },
      {
        value:'小时',
        text:'小时'
      },
      {
        value:'分钟',
        text:'分钟'
      },
      {
        value:'秒',
        text:'秒'
      },
    ]
    return(
      <Drawer
        visible={visible}
        title={title}
        onClose={this.onCloseDrawer}
        width={825}
      >
        <Form {...formItemLayout} style={{marginBottom:60}}>
          <Form.Item label="用户标签名称">
            {
              getFieldDecorator('tagName',{rules:[{required:true,message:'请填写标签名称'}]})(
                <Input placeholder="请输入" />
              )
            }
          </Form.Item>
          {
            id ? (
              <Form.Item label="标签ID">
                {
                  getFieldDecorator('id',{rules:[{required:true,message:'请填写标签字段值'}]})(
                    <Input placeholder="请输入" disabled />
                  )
                }
              </Form.Item>
            ):''
          }
          
          <div style={{paddingLeft:10,borderLeft:'3px solid'}}>条件组</div>
          {
            userTagItemList.map((item,index) => {
              return(
                <div key={item.group} style={groupStyle}>
                  {
                     index != 0 ? <div><span style={conditionStyle}>或</span><span style={dividerStyle}></span><Icon type="close" style={deleteStyle} onClick={() => this.removeConditionGroup(item.group)} /></div> : ''
                  }
                  <div style={{padding:10}}>
                    {
                      item.userTagConditionList.map((con,conIndex) => {
                        return(
                          <div key={con.id}>
                            {
                              conIndex != 0 ? <div><span style={{...conditionStyle,background:'#999999'}}>且</span></div> : ''
                            }
                            
                            {/** 员工属性 */}
                            <Form.Item style={inlineStyle}>
                              {
                                getFieldDecorator('columnName_'+item.group+'_'+con.id,{rules:[{required:true,message:'必填项'}]})(
                                  <Select style={{width:160}} placeholder="员工属性">
                                    {
                                      columnNameList.map(item => {
                                        return <Select.Option value={item.value} key={item.value}>{item.text}</Select.Option>
                                      })
                                    }
                                  </Select>
                                )
                              }
                            </Form.Item>
                            {/** 状态/值 */}
                            <Form.Item style={inlineStyle}>
                              {
                                getFieldDecorator('conditionType_'+item.group+'_'+con.id,{rules:[{required:true,message:'必填项'}]})(
                                  <Select style={{width:100}} placeholder="状态/值" onChange={(value) => this.changeConditionType(item.group,con.id)}>
                                    {
                                      conditionTypeList.map(item => {
                                        return <Select.Option value={item.value} key={item.value}>{item.text}</Select.Option>
                                      })
                                    }
                                  </Select>
                                )
                              }
                            </Form.Item>
                            {
                              /**状态-条件类型 */
                              getFieldValue('conditionType_'+item.group+'_'+con.id) == 0 ? (
                                <Form.Item style={inlineStyle}>
                                  {
                                    getFieldDecorator('conditionValueType_'+item.group+'_'+con.id,{rules:[{required:true,message:'必填项'}]})(
                                      <Select style={{width:120}} onChange={() => this.changeConditionValueType(item.group,con.id)} placeholder="选择条件">
                                        {
                                          conditionValueTypeList0.map(item => {
                                            return <Select.Option value={item.value} key={item.value}>{item.text}</Select.Option>
                                          })
                                        }
                                      </Select>
                                    )
                                  }
                                </Form.Item>
                              ) : ''
                            }
                            {
                              /**值-条件类型 */
                              getFieldValue('conditionType_'+item.group+'_'+con.id) == 1 ? (
                                <Form.Item style={inlineStyle}>
                                  {
                                    getFieldDecorator('conditionValueType_'+item.group+'_'+con.id,{rules:[{required:true,message:'必填项'}]})(
                                      <Select style={{width:160}} onChange={() => this.changeConditionValueType(item.group,con.id)} placeholder="选择条件">
                                        {
                                          conditionValueTypeList1.map(item => {
                                            return <Select.Option value={item.value} key={item.value}>{item.text}</Select.Option>
                                          })
                                        }
                                      </Select>
                                    )
                                  }
                                </Form.Item>
                              ) : ''
                            }
                            {
                              /**条件值 */
                              /**
                               * 1.若conditionValueType为 2: 包含(字符串型), 3: 不包含(字符串型) 展示输入多个字符串型
                               */
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 2 || 
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 3 ? (
                                <Form.Item style={{...inlineStyle,marginRight:0}}>
                                  {
                                    getFieldDecorator('conditionValue_'+item.group+'_'+con.id,{rules:[{required:true,message:'必填项'}]})(
                                      <Input style={{width:270}} placeholder="可输入多个字符串型,通过'|'符号隔开" />
                                    )
                                  }
                                </Form.Item>
                              ) : ''
                            }
                            {
                              /**条件值 */
                              /**
                               * 2.若conditionValueType为 4: 等于(字符串型), 5: 不等于(字符串型) 展示输入单个字符串型
                               */
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 4 || 
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 5 ? (
                                <Form.Item style={{...inlineStyle,marginRight:0}}>
                                  {
                                    getFieldDecorator('conditionValue_'+item.group+'_'+con.id,{rules:[{required:true,message:'必填项'}]})(
                                      <Input style={{width:270}} placeholder="请输入单个字符串型" maxLength={200} />
                                    )
                                  }
                                </Form.Item>
                              ) : ''
                            }
                            {
                              /**条件值 */
                              /**
                               * 3.若conditionValueType为 6: 等于(数值型), 7: 不等于(数值型), 8: 大于等于(数值型), 9: 小于等于(数值型), 10: 大于(数值型), 11: 小于(数值型) 展示输入数值型
                               */
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 6 || 
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 7 || 
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 8 || 
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 9 || 
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 10 || 
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 11 ? (
                                <Form.Item style={{...inlineStyle,marginRight:0}}>
                                  {
                                    getFieldDecorator('conditionValue_'+item.group+'_'+con.id,{rules:[{required:true,message:'必填项'}]})(
                                      <InputNumber style={{width:130}} placeholder="请输入数值型" />
                                    )
                                  }
                                </Form.Item>
                              ) : ''
                            }
                            {
                              /**条件值 */
                              /**
                               * 4.若conditionValueType为 12: 大于(时间段), 13: 小于(时间段), 14: 等于(时间段) 展示输入数值型 > 0
                               */
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 12 || 
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 13 || 
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 14 ? (
                                <Form.Item style={{...inlineStyle,marginRight:0}} wrapperCol={{span:24}}>
                                  <Form.Item style={inlineStyle}>
                                    {
                                      getFieldDecorator('conditionValue_'+item.group+'_'+con.id,{rules:[{required:true,message:'必填项'}]})(
                                        <InputNumber min={0} style={{width:130}} placeholder="请输入时间段" />
                                      )
                                    }
                                  </Form.Item>
                                  <Form.Item style={inlineStyle}>
                                    {
                                      getFieldDecorator('conditionValueOther_'+item.group+'_'+con.id,{rules:[{required:true,message:'必填项'}]})(
                                        <Select style={{width:80}} placeholder="单位">
                                          {
                                            unitList.map(item => {
                                              return <Select.Option value={item.value} key={item.value}>{item.text}</Select.Option>
                                            })
                                          }
                                        </Select>
                                      )
                                    }
                                  </Form.Item>
                                  
                                </Form.Item>
                              ) : ''
                            }
                            {
                              /**条件值 */
                              /**
                               * 5.若conditionValueType为 15: 早于(日期时间), 16: 晚于(日期时间), 17: 等于(日期时间) 展示输入日期选择框
                               */
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 15 || 
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 16 || 
                               getFieldValue('conditionValueType_'+item.group+'_'+con.id) == 17 ? (
                                <Form.Item style={{...inlineStyle,marginRight:0}} wrapperCol={{span:24}}>
                                  <Form.Item style={inlineStyle}>
                                    {
                                      getFieldDecorator('conditionValue_'+item.group+'_'+con.id,{rules:[{required:true,message:'必填项'}]})(
                                        <DatePicker style={{width:120}} />
                                      )
                                    }
                                  </Form.Item>
                                  <Form.Item style={inlineStyle}>
                                    {
                                      getFieldDecorator('conditionValueOther_'+item.group+'_'+con.id,{rules:[{required:true,message:'必填项'}]})(
                                        <TimePicker />
                                      )
                                    }
                                  </Form.Item>
                                </Form.Item>
                              ) : ''
                            }
                            {
                              conIndex === 0 ? '' : (
                                <Form.Item style={inlineStyle}>
                                  <Icon type="close" style={deleteStyle} onClick={() => this.removeConditionItem(item.group,con.id)} />
                                </Form.Item>
                              )
                            }
                          </div>
                        )
                      })
                    }
                  </div>
                  <Button icon="plus" type="link" onClick={() => this.addConditionItem(item.group)}>添加条件</Button>
                  {
                    index === userTagItemList.length - 1 ? <div style={{...dividerStyle,width:'100%'}}></div> : ''
                  }
                  
                </div>
              )
            })
          }
          <Button type="primary" ghost onClick={() => this.addConditionGroup()}>添加条件组</Button>
          
        </Form>


        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={this.onCloseDrawer} style={{ marginRight: 8 }}>
            取消
          </Button>
          <Button onClick={this.doValidate} type="primary" loading={loading}>
            确定
          </Button>
        </div>
      </Drawer>
    )
  }
}

export default Form.create()(EditLabel)